/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.gwt.apps.server.dataanalysis;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bioteam.appweb.Config;
import net.bioteam.appweb.gwt.apps.clientandserver.Constant;
import net.bioteam.appweb.gwt.apps.server.program.ProgramHandler;
import net.bioteam.common.user.User;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileInput extends HttpServlet
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final Log logger = LogFactory.getLog(FileInput.class);
	public static long MAX_FILE_SIZE_TO_SAVE = 1024 * 1024;

	protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException
	{
		ServletFileUpload upload = new ServletFileUpload();
		Map<String, String> values = new HashMap<String, String>();

		User user = (User) request.getSession().getAttribute("user");
		// Parse the request
		File dir = new File(Config.USER_TMP + File.separator + user.getName());
		if (!dir.exists())
		{
			dir.mkdirs();
		}

		try
		{
			FileItemIterator iter = null;
			iter = upload.getItemIterator(request);
			while (iter.hasNext())
			{
				FileItemStream item = iter.next();
				String name = item.getFieldName();
				InputStream stream = item.openStream();

				String filename = item.getName();
				if (filename != null)
				{
					filename = FilenameUtils.getName(filename.trim());
				}

				if (item.isFormField())
				{
					if (name.endsWith(Constant.file_data_suffix))
					{
						String paramName = name.substring(0, name.length() - Constant.file_data_suffix.length());
						File file = new File(dir.getAbsolutePath() + File.separator + paramName);
						BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
						Streams.copy(stream, out, true);
						if (file.length() == 0)
						{
							// empty element
							file.delete();
						} else
						{
							values.put(paramName, file.getAbsolutePath());
						}
					} else if (name.endsWith(Constant.file_server_suffix))
					{
						String value = Streams.asString(stream).trim();
						if (value.length() > 0)
						{
							String paramName = name.substring(0, name.length() - Constant.file_server_suffix.length());
							value = ProgramHandler.webStringToRealFile(value, user.getName());
							values.put(paramName, value);
						}
					} else
					{
						String value = Streams.asString(stream).trim();
						if (value.length() > 0)
						{
							values.put(name, value);
						}
					}
				} else
				{
					if (filename == null || filename.length() == 0)
						continue;
					File file = new File(dir.getAbsolutePath() + File.separator + filename);
					BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
					Streams.copy(stream, out, true);
					if (file.length() == 0)
					{
						// empty element
						file.delete();
					} else
					{
						values.put(name, file.getAbsolutePath());
					}

				}
			}

			if (values.get("data") == null)
			{
				String msg = ProgramHandler.getUploadRetMessage(false, "No input data", null);
				resp.setContentType("text/html");
				resp.setContentLength(msg.length());
				resp.getWriter().write(msg);
				return;
			}
			if (values.get("mobytype") == null)
			{
				String msg = ProgramHandler.getUploadRetMessage(false, "No type is selected", null);
				resp.setContentType("text/html");
				resp.setContentLength(msg.length());
				resp.getWriter().write(msg);
				return;
			}

			// always to use a new Analysis data so that we start the wizard
			// state from a clean state.
			
			AnalysisData oldData=(AnalysisData)request.getSession().getAttribute(AnalysisData.AnalysisSessionKey);
			if (oldData!=null)
			{
				if (oldData.inputfile!=null)
					new File(oldData.inputfile).delete();
			}
			AnalysisData data = new AnalysisData();
			request.getSession().setAttribute(AnalysisData.AnalysisSessionKey, data);
			data.setInputfile(values.get("data"));
			data.setMobytype(values.get("mobytype"));

			String msg = ProgramHandler.getUploadRetMessage(true, "No type is selected", "user_analysis_2");
			resp.setContentType("text/html");
			resp.setContentLength(msg.length());
			resp.getWriter().write(msg);

		} catch (Exception e)
		{
			String msg1 = e.getMessage();
			if (msg1 == null)
			{
				msg1 = "unknown server error";
			}
			logger.warn(msg1, e);
			String msg = ProgramHandler.getUploadRetMessage(false, msg1, null);
			resp.setContentType("text/html");
			resp.setContentLength(msg.length());
			resp.getWriter().write(msg);
		}

	}

}
